#include "settingdialog.h"
#include "util.h"
#include <QEvent>

SettingDialog::SettingDialog(QWidget *parent)
    :QDialog(parent)
{
    this->setMinimumSize(300,200);
    this->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

    language_label = new QLabel();
    language_comboBox = new QComboBox();
    info_label = new QLabel();

    language_comboBox->addItem("chinese",QVariant::fromValue(UI_ZH));//添加自定义的类型到combobox，否则只能通过index来区分，这样虽然简单了些，但是造成模糊不清的结果
    language_comboBox->addItem("english",QVariant::fromValue(UI_EN));

    QHBoxLayout * language_layout = new QHBoxLayout();
    language_layout->addStretch();
    language_layout->addWidget(language_label);
    language_layout->addWidget(language_comboBox);
    language_layout->addStretch();
    language_layout->setSpacing(5);
    language_layout->setContentsMargins(0,0,0,0);

    QVBoxLayout * main_layout = new QVBoxLayout();
    main_layout->addWidget(info_label,0,Qt::AlignCenter);
    main_layout->addLayout(language_layout);
    main_layout->setSpacing(10);
    main_layout->setContentsMargins(10,10,10,10);

    this->setLayout(main_layout);
    this->traslateUI();

    qRegisterMetaType<LANGUAGE>("LANGUAGE");

    connect(language_comboBox,static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),this,&SettingDialog::onIndexChanged);
//    connect(language_comboBox,(int)&QComboBox::currentIndex(),
//            this,onIndexChanged());

}


void SettingDialog::changeEvent(QEvent *event)
{
    switch (event->type()) {
    case QEvent::LanguageChange:
        traslateUI();
        break;
    default:
        QDialog::changeEvent(event);
        break;
    }
}


void SettingDialog::traslateUI()
{
    this->setWindowTitle(tr("setting dialog"));
    info_label->setText(tr("no brothers no programming"));
    language_label->setText(tr("language"));
    language_comboBox->setItemText(0,tr("chinese"));
    language_comboBox->setItemText(1,tr("englist"));
}


void SettingDialog::onIndexChanged()
{
    LANGUAGE language = language_comboBox->currentData().value<LANGUAGE>();

//    qDebug() << language << "--------";


    emit switchLanguage(language);
}


void SettingDialog::loadConfig()
{
    QString language_value;
    QString language_suffix = QString("zh");
    LANGUAGE language = UI_ZH;//默认值
    bool is_read = Util::readInit(QString("./user.ini"),
                                  QString("language"),language_value);//一个路径，一个key，一个value的引用

    if (is_read) {
        language = (LANGUAGE)language_value.toInt();
        if (language == UI_EN) {
            language_suffix = QString("en");
        }
    }

    /*
     * 如果LANGUAGE和 language_comboBox的index相对应的话，那么直接可以设置LANGUAGE的值为language_comboBox的当前index
*/

    int count = language_comboBox->count();
    for (int i = 0; i < count; ++i) {
        if (language == i) {
            language_comboBox->setCurrentIndex(language);
            break;
        }
    }

}
